package com.DBM;


import java.sql.*;

import com.mysql.jdbc.Driver;

/**
 * Created by asus on 2017-02-08.
 */
public class DBManager {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //打开数据库
        public Connection openconnection() throws SQLException {
            String url="jdbc:mysql://localhost:3306/cake";
            return DriverManager.getConnection(url, "root", "123456");
    }
        public void closeconnection(Connection conn) throws SQLException{
        if (conn != null && !conn.isClosed()){
            conn.close();
        }
        }
    //执行查询命令
    /*
    * conn  连接对象
    * sql   命令
    * objects   参数（被查询的是什么，WHERE后的东西）
    * */
    public ResultSet query(Connection conn,String sql,Object...objects) throws SQLException{
        ResultSet rs = null;
        if(!conn.isClosed() && conn!=null){
            System.out.println(sql);
            PreparedStatement ps = conn.prepareStatement(sql);
            if(objects!=null){
                for (int i = 0; i < objects.length; i++) {
                    ps.setObject(i+1, objects[i]);
                }
            }
            rs=ps.executeQuery();
        }
        return rs;
    }

    public int execute(Connection conn,String sql,Object...objects)throws SQLException{
        int rs = 0;
        if (!conn.isClosed() && conn !=null){
            PreparedStatement ps = conn.prepareStatement(sql);
            if (objects !=null){
                for (int i = 0; i < objects.length ; i++) {
                    ps.setObject(i+1,objects[i]);
                }
            }
            rs = ps.executeUpdate();
        }
        return rs;
    }
}